<template>
  <div class="nav-menu">
    <a-menu v-model:selectedKeys="selectedKeys" theme="dark" mode="inline">
      <template v-for="item of menus" :key="item.id">
        <a-sub-menu v-if="item.type !== 2" :key="item.url">
          <!-- sub-menu title -->
          <template #title>
            <span>
              <component :is="item.icon"></component>
              <span>{{ item.name }}</span>
            </span>
          </template>

          <template v-for="menuItem of item.children" :key="menuItem.url">
            <a-menu-item
              v-if="menuItem.type === 2"
              :key="menuItem.url"
              @click="
                handleMenuItemClick(menuItem.id, menuItem.name, menuItem.url)
              "
            >
              <component :is="menuItem.icon"></component>
              <span>{{ menuItem.name }}</span>
            </a-menu-item>
          </template>
        </a-sub-menu>
      </template>
    </a-menu>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import { NavHeader } from '@/components/nav-header'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useStore } from '@/store'

export default defineComponent({
  props: {
    // selectedKeys: {
    //   type: Array as PropType<string[]>,
    //   default: () => ['2']
    // }
    // menus: {
    //   type: Array,
    //   required: true
    // }
  },
  components: { NavHeader },
  emits: ['clickMenuItem'],
  setup(props, { emit }) {
    const store = useStore()
    const route = useRoute()
    const menus = store.state.login.userMenu
    const selectedKeys = ref<string[]>([])
    let selected = ref(0)

    watch(
      () => route.path,
      () => {
        selectedKeys.value = []
        selectedKeys.value.push(route.path)
      }
    )

    const handleMenuItemClick = (id: number, name: string, url: string) => {
      selected.value = id

      router.push({
        path: url ?? 'not-found'
      })

      emit('clickMenuItem', { id: id, name: name, url: url })
    }

    return { handleMenuItemClick, menus, selectedKeys }
  }
})
</script>
<style scoped lang="less">
.logo {
  height: 32px;
  margin: 16px;
  // background: rgba(255, 255, 255, 0.3);
}

.site-layout .site-layout-background {
  background: #fff;
}
[data-theme='dark'] .site-layout .site-layout-background {
  background: #141414;
}
</style>
